#include <iostream>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <iostream>
#include <stdlib.h>


struct clientData
{
	size_t port;
        size_t length;
};

void* startClient(void* data)
{
    clientData const* cd = (clientData*)data;
    size_t request_length = cd->length;
    size_t port = cd->port;

        sockaddr_in cliaddr;
        bzero(&cliaddr, sizeof(cliaddr));
        cliaddr.sin_family = AF_INET;
        cliaddr.sin_port = htons(port);

        int sockfd = socket(AF_INET, SOCK_STREAM, 0);

        if (connect(sockfd, (sockaddr*) &cliaddr, sizeof(cliaddr)))
        {
                std::cout << "Error while connecting!" << std::endl;
                return 0;
        }

        char message[request_length + 1];
        for (size_t i = 0; i < request_length; ++i)
            message[i] = 'a' + (i % 10);
        message[request_length] = '\0';

        //std::cout << message << std::endl;

        send(sockfd, message, strlen(message) + 1, 0);

        char buffer[1024];
        int length = recv (sockfd, buffer, 1024, 0);
        if (length < 0)
        {
            std::cout << "No answer" << std::endl;
            return 0;
        }

        //std::cout << "Datagramm - " << buffer << std::endl;
        close(sockfd);

        return 0;
}

void waitTime(size_t timeout)        
{
    size_t micros = timeout * 1000;
    usleep(micros);
}

int main (int argc, char** argv)
{
        if (argc <= 5)
        {
                std::cout << "Usage: clientUtil cl_count req_len interval sync port" << std::endl;
                return 1;
        }

        size_t cl_count = atoi(argv[1]);
        std::cout << "Amount of clients: " << cl_count << std::endl;

        size_t req_len = atoi(argv[2]);
        std::cout << "Request length: " << req_len << std::endl;

        size_t interval = atoi(argv[3]);
        std::cout << "Interval: " << interval << std::endl;

        bool sync = strcmp(argv[4], "sync") == 0;
        std::cout << (sync ? "Sync" : "Async") << std::endl;

        size_t port = atoi(argv[5]);
        std::cout << "Port: " << port << std::endl;

        clientData cd;
        cd.length = req_len;
        cd.port = port;

        if (sync)
        {
            for (size_t i = 0; i < cl_count; ++i)
            {
                startClient(&cd);
                waitTime(interval);
            }
        }
        else
        {
            //create threads
            pthread_t threads[cl_count];

            for (size_t i = 0; i < cl_count; ++i)
            {
                pthread_create(&threads[i], 0, startClient, (void*)&cd);
                waitTime(interval);
            }

            for (size_t i = 0; i < cl_count; ++i)
                pthread_join(threads[i], 0);
        }

        return 0;
}
